package com.lifang.imgsoa.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class SystemUtil {

	private static Logger logger = Logger.getLogger(SystemUtil.class);

	/** 常量配置文件 */
	public final static ResourceBundle config = ResourceBundle.getBundle("config");

	private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	public static void main(String[] args) {
		String mobile = "15001895675";
		System.out.println(encryptMobile(mobile));
	}

	/**
	 * 获取系统属性。该方法主要被velocity模版所使用。
	 * 
	 * @param key
	 *            属性key
	 * @return 系统属性值.
	 */
	public static String getSystemProperty(String key) {
		return config.getString(key);
	}

	/** 加密手机 */
	public static String encryptMobile(String mobile) {
		StringBuffer sb = new StringBuffer();
		sb.append(mobile.substring(0, 4)).append("****").append(mobile.substring(8));
		return sb.toString();
	}

	public static String transferDate(Date date) {
		return format.format(date);
	}

	/**
	 * 设置浏览器输出头
	 */
	public static void setCacheHeader(HttpServletResponse resp, long cacheTime) {
		if (cacheTime <= 0) {
			setNoCacheHeader(resp);
			return;
		}
		long now = new Date().getTime();
		resp.setDateHeader("Expires", now + cacheTime);
		resp.setDateHeader("Last-Modified", now);
		resp.setHeader("Cache-Control", "max-age=" + (cacheTime / 1000));
	}

	public static void setNoCacheHeader(HttpServletResponse resp) {
		resp.setHeader("Pragma", "No-Cache");
		resp.setHeader("Cache-Control", "no-cache, no-store");
		resp.setDateHeader("Expires", 0);
	}

	public static void writeResponse(HttpServletRequest req, HttpServletResponse resp, String content) {
		writeResponse(req, resp, content, 0, null);
	}

	public static void writeResponse(HttpServletRequest req, HttpServletResponse resp, String content, String jsoncallback) {
		writeResponse(req, resp, content, 0, jsoncallback);
	}

	/**
	 * 写ajax响应
	 * 
	 * @param content
	 */
	public static void writeResponse(HttpServletRequest req, HttpServletResponse resp, String content, long cacheTime, String jsoncallback) {
		String charset = req.getParameter("charset");

		PrintWriter writer = null;
		try {
			resp.setHeader("P3P", "CP=CAO PSA OUR");
			if (StringUtils.isNotBlank(charset)) {
				resp.setCharacterEncoding(charset);
			} else {
				resp.setCharacterEncoding("UTF-8");
			}

			resp.setContentType("text/plain");
			setCacheHeader(resp, cacheTime);
			writer = resp.getWriter();
			writer.write(content);
		} catch (IOException e) {
			logger.error("writeResponse error:", e);
		} finally {
			IOUtils.closeQuietly(writer);
		}
	}

}
